#include "medicineadd.h"
#include "ui_medicineadd.h"
#include <QMessageBox>

MedicineAddWindow::MedicineAddWindow(QWidget *parent)
    : QWidget(parent)
    , medicineaddwindowUi(new Ui::MedicineAddWindow)
    , networkManager(new NetworkManager(this))
{
    medicineaddwindowUi->setupUi(this);
    connect(networkManager, &NetworkManager::addMedicineResponseReceived, this, &MedicineAddWindow::handleAddMedicineResponse);
}

MedicineAddWindow::~MedicineAddWindow()
{
    delete medicineaddwindowUi;
}

void MedicineAddWindow::on_submit_clicked()
{
    QString name = medicineaddwindowUi->nameLineEdit->text();
    QString category = medicineaddwindowUi->categoryLineEdit->text();
    QString supplier = medicineaddwindowUi->supplierLineEdit->text();
    double price = medicineaddwindowUi->priceLineEdit->text().toDouble();
    int stock = medicineaddwindowUi->stockLineEdit->text().toInt();
    int threshold = medicineaddwindowUi->thresholdLineEdit->text().toInt();
    int validity = medicineaddwindowUi->validityLineEdit->text().toInt();

    if (name.isEmpty() || category.isEmpty() || supplier.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请填写所有必填字段");
        return;
    }

    QJsonObject medicineInfo;
    medicineInfo["name"] = name;
    medicineInfo["category"] = category;
    medicineInfo["supplier"] = supplier;
    medicineInfo["price"] = price;
    medicineInfo["stock"] = stock;
    medicineInfo["threshold"] = threshold;
    medicineInfo["validity"] = validity;

    networkManager->addMedicine(medicineInfo);
}

void MedicineAddWindow::on_resetButton_clicked()
{

    medicineaddwindowUi->nameLineEdit->clear();
    medicineaddwindowUi->categoryLineEdit->clear();
    medicineaddwindowUi->supplierLineEdit->clear();
    medicineaddwindowUi->priceLineEdit->clear();
    medicineaddwindowUi->stockLineEdit->clear();
    medicineaddwindowUi->thresholdLineEdit->clear();
    medicineaddwindowUi->validityLineEdit->clear();
}

void MedicineAddWindow::handleAddMedicineResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QMessageBox::information(this, "成功", "药品添加成功！");
        on_resetButton_clicked();
    } else {
        QMessageBox::warning(this, "错误", "药品添加失败：" + desc);
    }
}
